<?php
/** Intervention_list
	* 
	* @package Pharmacy Intervention 
	* @subpackage Controller
	* @category Intervention 
	* @author Ray Nowell 
	*/  
class Intervention_list extends MY_Controller {

	function Intervention_list()
	{
		parent::MY_Controller();
	}
		
	/**
	* Returns javascript used to perform the operations on the Date Duration control.
	* The javascript returned will be placed in the doc ready function. 
	* 
	* @access private 
	* @return string */ 
	function _get_date_duration_doc_ready_javascript($default_checked_option, $selected_duration, $range_start_date, $range_end_date)
	{
		$return_value = '$(".datebox").datepicker({
								showOn: "button",
								buttonImage: "'.base_url().'css/custom-theme/images/calendar.gif",
								buttonImageOnly: true
								});

								$("#_durationButtonRefresh").click(function() 
									{
										var d1 = new	Date($("#_durationStartDate").val());
										var d2 = new	Date($("#_durationEndDate").val());
										if (d1 > d2)
										{
											window.alert("Start Date must be less or equal to End Date.");
											$("#_durationStartDate").focus();
											return false;
										} 

										var segments;
										if	($("#_durationDropDown").attr("disabled") == "")
											segments = "/" + $("#_durationDropDown").val();
										else
											segments = "/range";

										segments = segments + "/" + $("#_durationStartDate").val().replace(/\//g,"_") + "/" + $("#_durationEndDate").val().replace(/\//g,"_")
										window.location.replace("'.base_url().'index.php/intervention_list/refresh" + segments); 
									});

									$(".optionDateRange").click(function()
									{
										if ( $(this).attr("id") == "_optDuration" ) 
										{
											$("#_durationDropDown").attr("disabled","");
											$(".datebox").datepicker( "disable" );
											setSpecificRange($("#_durationDropDown").val());
										}
										else
										{
											$("#_durationDropDown").attr("disabled","disabled");
											$(".datebox").datepicker( "enable" );
											}
									});

									$("#'.$default_checked_option.'").attr("checked","checked");
									$("#_durationStartDate").val("'.$range_start_date.'");
									$("#_durationEndDate").val("'.$range_end_date.'");
									$("#_durationDropDown").val("'.$selected_duration.'");
									$("#'.$default_checked_option.'").click();
									';

		//http://stackoverflow.com/questions/222309/calculate-last-day-of-month-in-javascript          
		$return_value .= '$("#_durationDropDown").change(function()
								{
									setSpecificRange($(this).val());					            
								});

								$("button", ".durationFrameSet").button();';
		
		return $return_value;
	}

/**
	* Javascript functions for Date Duration control called outside of the doc ready function.
	* 
	* @access private 
	* @return string */ 
	function _get_additional_date_duration_javascript()
	{
		$return_value = 'function setSpecificRange(durationToUse)
											{
												var d = new Date();
												var lastDayOfThisMonth = new Date(d.getFullYear(), d.getMonth() + 1, 0);
												var lastDayOfLastMonth = new Date(d.getFullYear(), d.getMonth(), 0);
												var stateDate;
												var endDate;
												switch(durationToUse)
												{
													case "today":
														stateDate = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
														endDate = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear(); 
														break;
													case "qtr_1": 
														stateDate = "01/01/2010";
														endDate = "03/31/2010";
														break;
													case "qtr_2": 
														stateDate = "04/01/2010";
														endDate = "06/30/2010"; 
														break;
													case "qtr_3": 
														stateDate = "07/01/2010";
														endDate = "09/30/2010"; 
														break;
													case "qtr_4": 
														stateDate = "10/01/2010";
														endDate = "12/31/2010"; 
														break;
													case "ytd": 
														stateDate = "01/01/2010";
														endDate = "12/31/2010"; 
														break;
													case "this_month":
														var localMonth = (d.getMonth() + 1) < 10 ? "0" + (d.getMonth() + 1) : (d.getMonth() + 1);
														stateDate = localMonth + "/01/" + d.getFullYear();
														endDate = localMonth + "/" + lastDayOfThisMonth.getDate() + "/" + d.getFullYear();
														break;
													case "last_month": 
														var localMonth = (d.getMonth()) < 10 ? "0" + (d.getMonth()) : (d.getMonth());
														stateDate = localMonth + "/01/" + d.getFullYear();
														endDate = localMonth + "/" + lastDayOfLastMonth.getDate() + "/" + d.getFullYear(); 
														break;
													case "all": 
														stateDate = "01/01/0001";
														endDate = "12/31/9999";
														break; 
											}
											$("#_durationStartDate").val(stateDate);
											$("#_durationEndDate").val(endDate);
											};';
		return $return_value;
	}
	
	function _get_copy_intervention_javascript()
	{
		$popupWidth		=	675;
		$popupHeight	=	370;
		
		$ret_val	= 'function copySelectedRecords()
						{
							var viewIds = new Array();
							var arrayCounter = 0;
							$(".GridCheckbox").each( function() 
															{
																if ($(this).is(":checked"))
																{					 
														 			viewIds[arrayCounter] = $(this).attr("name").replace("_chkIntervention","");
														 			arrayCounter++;
																}
													});
													var viewUrl = "'.site_url('intervention/copy').'/" + viewIds.join("/");	
													var popupLeft = parseInt((screen.availWidth/2) - ('.$popupWidth.'/2));
								var popupTop = parseInt((screen.availHeight/2) - ('.$popupHeight.'/2));
									window.open(viewUrl,\'popup\',\'width=\' + '.$popupWidth.' + \',height=\' + '.$popupHeight.' + \',scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=\' + popupLeft + \',top=\' + popupTop + \'\');
									window.status = window.status=("Connecting...");
									return false;
													
							
						}';
		
		return $ret_val;
		
	}
		
	/**
	* Used for _optDuration, this array accepts a duration type and returns an array to ste values in the UI 
	*   and filter the mysql results on load
	* 
	* @access private 
	* @param string
	* @return string */ 
	function _set_duration_array($duration_type)
	{
		$today = getdate();
		$current_month = $today['mon'] < 10 ? '0'.$today['mon'] : $today['mon'] ;
		$current_year = $today['year'];
		$current_day = $today['mday'] < 10 ? '0'.$today['mday'] : $today['mday'] ;
		
		switch ($duration_type) 
		{
			case 'today':
				$duration_start_date = $current_month.'/'.$current_day.'/'.$current_year;
				$duration_end_date = $current_month.'/'.days_in_month($current_month,$current_year).'/'.$current_year;
				$mysql_start_date = $current_year.'-'.$current_month.'-'.$current_day;
				$mysql_end_date = $current_year.'-'.$current_month.'-'.$current_day;
				break;
			case 'this_month':
				$duration_start_date = $current_month.'/01/'.$current_year;
				$duration_end_date = $current_month.'/'.days_in_month($current_month,$current_year).'/'.$current_year;
				$mysql_start_date = $current_year.'-'.$current_month.'-01';
				$mysql_end_date = $current_year.'-'.$current_month.'-'.days_in_month($current_month,$current_year);
				break;
			case 'last_month':
				//set last month values
				$current_month = $current_month == '01' ? '12' : $current_month - 1;
				$current_year = $current_month == '01' ? $current_year - 1 : $current_year;
				$current_month = $current_month < 10 ? '0'.$current_month : $current_month ;
				    
				$duration_start_date = $current_month.'/01/'.$current_year;
				$duration_end_date = $current_month.'/'.days_in_month($current_month,$current_year).'/'.$current_year;
				$mysql_start_date = $current_year.'-'.$current_month.'-01';
				$mysql_end_date = $current_year.'-'.$current_month.'-'.days_in_month($current_month,$current_year);
				break;
			case 'qtr_1':
				$duration_start_date = '01/01/'.$current_year;
				$duration_end_date = '03/31/'.$current_year;
				$mysql_start_date = $current_year.'-01-01';
				$mysql_end_date = $current_year.'-03-31';
				break;
			case 'qtr_2':
				$duration_start_date = '04/01/'.$current_year;
				$duration_end_date = '06/30/'.$current_year;
				$mysql_start_date = $current_year.'-04-01';
				$mysql_end_date = $current_year.'-06-30';
				break;
			case 'qtr_3':
				$duration_start_date = '07/01/'.$current_year;
				$duration_end_date = '09/30/'.$current_year;
				$mysql_start_date = $current_year.'-07-01';
				$mysql_end_date = $current_year.'-09-30';
				break;
			case 'qtr_4':
				$duration_start_date = '10/01/'.$current_year;
				$duration_end_date = '12/31/'.$current_year;
				$mysql_start_date = $current_year.'-10-01';
				$mysql_end_date = $current_year.'-12-31';
				break;
			case 'ytd':
				$duration_start_date = '01/01/'.$current_year;
				$duration_end_date = '12/31/'.$current_year;
				$mysql_start_date = $current_year.'-01-01';
				$mysql_end_date = $current_year.'-12-31';
				break;
			case 'all':
				$duration_start_date = '01/01/0001';
				$duration_end_date = '12/31/9999';
				$mysql_start_date = '0001-01-01';
				$mysql_end_date = '9999-12-31';
				break;
		}
		
		$ret_val = array(	'duration_start' => $duration_start_date, 
											'duration_end' 	 => $duration_end_date,
											'mysql_start' 	 => $mysql_start_date,
											'mysql_end' 	 => $mysql_end_date
										);
		return $ret_val;
	}

	/*
	 * PUBLIC FUNCTIONS (e.g. can be accessed from the browser
	 */
	
	function index()
	{
		//$this->output->enable_profiler(TRUE);  
		
		define("POPUP_HEIGHT", 700);
		define("POPUP_WIDTH", 950);
		
		$this->load->helper('form');
		$this->load->helper('cookie');
		$this->load->helper('date');
				
		$data['title'] = COMPANY_NAME.' -- Intervention List';
		$data['heading'] = 'Interventions';
		
		$data['duration_options'] = array(
																			'today'  		=>	'Today',
																			'this_month'	=>	'This Month',
																			'last_month'	=>	'Last Month',
																			'qtr_1'			=>	'Qtr. 1',
																			'qtr_2'			=>	'Qtr. 2',
																			'qtr_3'			=>	'Qtr. 3',
																			'qtr_4'			=>	'Qtr. 4',
																			'ytd'			=>	'Ytd.',
																			'all'			=>	'All'
																			);

		//Get duration cookie and set appropriate vars based on what's found                                        
		$duration_cookie = get_cookie(DURATION_COOKIE);
		if (!$duration_cookie)
		{
			//Set default value for no cookie found
			$selected_duration = 'this_month';
			$duration_array = $this->_set_duration_array('this_month');
			$default_checked_option = '_optDuration';
		}
		else
		{
			//Put the cookie value into an array
			$duration_cookie = explode("|", $duration_cookie);
			
				
			//If the first element of the array == "range", then  
			if ($duration_cookie[0] != 'range')
				{
					$duration_array = $this->_set_duration_array($duration_cookie[0]);
					$selected_duration = $duration_cookie[0];
					$default_checked_option = '_optDuration';
				}
				else
				{
					$selected_duration = 'this_month'; //Set default...this does not matter since we're on a range
					$default_checked_option = '_optDateRange';
					$mysql_start_date = strtotime($duration_cookie[1]);
					$mysql_end_date = strtotime($duration_cookie[2]);
					
					$mysql_start_date = date('Y-m-d',$mysql_start_date);
					$mysql_end_date	 = date('Y-m-d',$mysql_end_date);
					
					$duration_array = array(	'duration_start' => $duration_cookie[1], 
							'duration_end' 	 => $duration_cookie[2],
							'mysql_start' 	 => $mysql_start_date,
							'mysql_end' 	 => $mysql_end_date
							);
				}
		}
		
		$data['selected_duration'] = $selected_duration;

		
		$auto_add 		=	$this->session->flashdata('auto_add');
		$auto_add_js	=	$auto_add ? '$(\'#_gridAddTop\').click();' : '';
		$data['additional_javascript_doc_ready_functions'] = get_grid_doc_ready_javascript().$this->_get_date_duration_doc_ready_javascript($default_checked_option, $selected_duration, element('duration_start', $duration_array), element('duration_end', $duration_array)).$auto_add_js;
		$data['additional_jquery_javascript'] = get_grid_functions('intervention', POPUP_HEIGHT, POPUP_WIDTH).$this->_get_additional_date_duration_javascript().$this->_get_copy_intervention_javascript();
		
		//removing link..will add java script to do the links
		$data['add_link'] = '<input id="_gridAddTop" type="image" border="0" language="javascript" onclick="return false;" alt="Insert" title="Insert" src="'.base_url().'images/add.png"  style="cursor: pointer;"/>';
		$data['view_link'] = '<input class="GridButton" id="_gridViewTop" type="image" disabled="disabled" border="0" language="javascript" onclick="return false;" alt="View" title="View" src="'.base_url().'images/view_disabled.png"  style="cursor: pointer;"/>';
		$data['copy_link'] = '<input class="GridButton" id="_gridCopyTop" type="image" disabled="disabled" border="0" language="javascript" onclick="return false;" alt="Copy" title="Copy" src="'.base_url().'images/copy_disabled.png"  style="cursor: pointer;"/>';
		$data['delete_link'] = '<input class="GridButton" id="_gridDeleteTop" type="image" disabled="disabled" border="0" language="javascript" onclick="return false;" alt="Delete" title="Delete" src="'.base_url().'images/delete_disabled.png"  style="cursor: pointer;"/>';

		$this->load->library('table');
		$this->table->set_heading('<input type="checkbox" id="_chkMaster">','Patient','Int. Date','Intervention Code','Status','Physician','Unit/Patient Loc.','Pharmacist','O.Drug','O.Cost/D','R.Drug','R.Cost/D','Savings');
		
		$this->load->model('Intervention_model');
		
		//$this->output->enable_profiler(TRUE);  
		$intervention_array = $this->Intervention_model->get_intervention_list(element('mysql_start', $duration_array), element('mysql_end', $duration_array));
		
		$accepted_savings_for_period = 0;
		
		//loop through the results and checkbox the id
		foreach($intervention_array  as $row)
		{
			 $java_script_text  = 'popup_edit_single('.$row['intervention_id'].');return false;'; //Must do this before replacing text on line below
			 $row['intervention_id']= '<input class="GridCheckbox" type="checkbox" name="_chkIntervention'.$row['intervention_id'].'" >';
	 				$edit_link_atts = array('title' => 'Edit',
														'onclick' => $java_script_text 
														);
			 $row['patient_id_number'] = anchor('requirements',$row['patient_id_number'],$edit_link_atts);
			 
       
			 $savings_value	=	$row['savings'];
			 if ($savings_value	===	'RM')
			 	$row['savings']	=	'class="savings-cell"'.$savings_value;
			 else if (is_numeric($savings_value))
			 {
          $savings_value = format_currency($savings_value);
			 	switch ($row['status']) 
			 	{
			 		case 'A':
			 			$accepted_savings_for_period = $accepted_savings_for_period + $savings_value;
			 			break;
			 		case 'P':
			 			break;
			 		case 'R':
			 			break;
			 	}	
			 	$row['savings']	=	'class="savings-cell"'.($savings_value<0?'-negative(':'').$savings_value.($savings_value<0?')':'');
			 }
			 
			 	
			 
			 $this->table->add_row($row);
		}
		
		$local_table_template = set_table_template();
		$this->table->set_template($local_table_template); 
		$local_table	=	$this->table->generate();
		$local_table	=	str_replace('<td><input class="GridCheckbox"','<td class="GridCheckboxTd"><input class="GridCheckbox"',$local_table);
		$local_table	=	str_replace('<td>class="savings-cell"-negative','<td class="savings-cell-negative">',$local_table);
		$local_table	=	str_replace('<td>class="savings-cell"','<td class="savings-cell">',$local_table);
		
		$data['ci_list']	=	$local_table;	
		$data['accepted_savings_for_period']	=	format_currency($accepted_savings_for_period);
		
		//Check flash data to see if there is any text to display to the user 
		$deleted_info = $this->session->flashdata('deleted_info');
		if (!empty($deleted_info))
			$data['deleted_info']	=	$deleted_info;
		
		$data['view'] = 'intervention_list_view';
		$this->load->vars($data);
		$this->load->view('master_view', $data);  
		
		
	}
	
	function delete()
	{
		$this->load->model('Intervention_model');
		$ret_val	=	$this->Intervention_model->Delete_intervention();
		
		if (count($ret_val) > 0)
			$this->session->set_flashdata('deleted_info', $ret_val);
		
		redirect('intervention_list');
	}

	function refresh()
	{
		$this->load->helper('cookie');
		$this->load->helper('date');
		
		delete_cookie(DURATION_COOKIE);
		
		$duration_var = $this->uri->segment(3);
		
		if ($duration_var == 'range') 
			$duration_var = 'range'.'|'.str_replace('_','/',$this->uri->segment(4)).'|'.str_replace('_','/',$this->uri->segment(5));
			
		$dution_cookie = array(
									 'name'	 => DURATION_COOKIE,
									 'value'	=> $duration_var,
									 'expire' => 60*60*24*30//Expire in thirty days
							 );

		set_cookie($dution_cookie);
		redirect('intervention_list');
	}

	//Sets the var to automatically load the CI Add form 
	function auto_add()
	{
		$this->session->set_flashdata('auto_add', true);
		redirect('intervention_list');
	}
}

/* End of file intervention_list.php */
/* Location: ./system/application/controllers/intervention_list.php */